package com.zt.fbg.config;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.stream.Collectors;

@Component
public class GatewayPropertRefresher {

    private static final Logger logger = LoggerFactory.getLogger(GatewayPropertRefresher.class);

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ContextRefresher contextRefresher;

    /**
     * 监听路由修改
     *
     * @param changeEvent
     */
    @ApolloConfigChangeListener(value = "application")
    public void onChange(ConfigChangeEvent changeEvent) {
        boolean gatewayPropertiesChanged = false;
        for (String changedKey : changeEvent.changedKeys()) {
            if (changedKey.startsWith("spring.cloud.gateway")) {
                gatewayPropertiesChanged = true;
                break;
            }
        }

        if (gatewayPropertiesChanged) {
            refresh(changeEvent);
        }
    }

    /**
     * 刷新路由信息
     *
     * @param changeEvent
     */
    private void refresh(ConfigChangeEvent changeEvent) {
        logger.info("Refreshing gateway properties!");
        eventPublisher.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        contextRefresher.refresh();
        logger.info("gateway properties refreshed!");
    }


}